﻿using System;
using System.Collections.Generic;
using System.Data;
using UFIDA.U8.MomServiceCommon;
using U8Login;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using FERROU8API.Pub;

namespace FERROU8API.Plugin
{
    public class CustomerPlugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Customerapi";
        //private readonly string _ip = "http://10.10.73.26:8888/api/" + "Customerapi";
        public static string constr = "";
        private string url = "";

        private String GetCustJs(clsLogin login, MSXML2.IXMLDOMDocument2 domhead, int operation)
        {

            var datatable = Common.GetUrl(constr, login.get_cAcc_Id()).Tables[0];
            var datarow = datatable.Rows[0];
            url = datarow[1] + "receiveCustomer/";
        

            String custcode = domhead.selectSingleNode("//ccuscode").nodeTypedValue.ObjToString();//客户编号-plf(修改)
            
            DebugWriteLog.WriteLine("custcode:" + custcode);
            List<Customer> custdatas = new List<Customer>();
            if (operation != 1) //不是删除
            {
                String custname = domhead.selectSingleNode("//ccusname").nodeTypedValue.ObjToString();
                String ccusabbname = domhead.selectSingleNode("//ccusabbname").nodeTypedValue.ObjToString();
                //客户简称-plf-2017-11-10
                string ccode = domhead.selectSingleNode("//ccccode").nodeTypedValue.ObjToString();

                var reserved5 = domhead.selectSingleNode("//ccusdefine12").nodeTypedValue.ObjToFloat();

                string MnemonicCode = domhead.selectSingleNode("//ccusmnemcode").nodeTypedValue.ObjToString(); 
                Int32 StartFlag = 1;

                Customer data = new Customer();
                data.CustomerCCode = ccode;
                data.CustomerName = custname;
                data.ShortName = ccusabbname;
                data.StartFlag = StartFlag;
                data.CustomerCode = custcode;
                data.MnemonicCode = MnemonicCode;

                data.Reserved5 = reserved5;

                //#region add by fulj 20210906 增加客户收货地址列表
                //string sql = "select a.cAddCode, a.cDeliverAdd, b.cContactName, b.cMobilePhone from CusDeliverAdd a  left join Crm_Contact b on b.cCusCode = a.cCusCode and b.cContactCode = a.cLinkPerson where a.ccuscode = '" + ccode + "'";
                //DataTable dt = UFIDA.U8.DB.DbHelperSQL.QueryAsDT(sql, login.UFDataConnstringForNet);
                //if (dt!= null && dt.Rows.Count > 0)
                //{
                //    data.address = new List<Address>();
                //    foreach (DataRow dr in dt.Rows)
                //    {
                //        Address add = new Address();
                //        add.cAddCode = dr["cAddCode"].ObjToString();
                //        add.cDeliverAdd = dr["cDeliverAdd"].ObjToString();
                //        add.cLinkPerson = dr["cContactName"].ObjToString();
                //        add.cMobilePhone = dr["cMobilePhone"].ObjToString();
                //        data.address.Add(add);
                //    }
                //}
                //#endregion

                custdatas.Add(data);
            }
            else
            {
                custdatas.Add(new Customer{CustomerCode = custcode});
            }
            ApiRequest req = new ApiRequest();
            req.data = custdatas;//.ToJson();
            req.orgcode = login.get_cAcc_Id();
            req.primarykey = custcode;
            req.operation = operation;
            DebugWriteLog.WriteLine("客户档案", "GetCustJs", req.ToJson());
            return req.ToJson();
        }


        private String GetCustJs_sh(clsLogin login, MSXML2.IXMLDOMDocument2 domhead, int operation)
        {

            var datatable = Common.GetUrl(constr, login.get_cAcc_Id()).Tables[0];
            var datarow = datatable.Rows[0];
            url = datarow[1] + "receiveCustomer";


            String custcode = domhead.selectSingleNode("//ccuscode").nodeTypedValue.ObjToString();//客户编号-plf(修改)

            DebugWriteLog.WriteLine("custcode:" + custcode);
            List<Customer> custdatas = new List<Customer>();
            if (operation != 1) //不是删除
            {
                String custname = domhead.selectSingleNode("//ccusname").nodeTypedValue.ObjToString();
                String ccusabbname = domhead.selectSingleNode("//ccusabbname").nodeTypedValue.ObjToString();
                //客户简称-plf-2017-11-10
                string ccode = domhead.selectSingleNode("//ccccode").nodeTypedValue.ObjToString();

                var reserved5 = domhead.selectSingleNode("//ccusdefine12").nodeTypedValue.ObjToFloat();

                string MnemonicCode = domhead.selectSingleNode("//ccusmnemcode").nodeTypedValue.ObjToString();
                Int32 StartFlag = 1;

                Customer data = new Customer();
                data.CustomerCCode = ccode;
                data.CustomerName = custname;
                data.ShortName = ccusabbname;
                data.StartFlag = StartFlag;
                data.CustomerCode = custcode;
                data.MnemonicCode = MnemonicCode;

                data.Reserved5 = reserved5;

                #region add by fulj 20210906 增加客户收货地址列表
                string sql = "select a.cAddCode, a.cDeliverAdd, b.cContactName, b.cMobilePhone from CusDeliverAdd a with (nolock) left join Crm_Contact b with (nolock) on b.cCusCode = a.cCusCode and b.cContactCode = a.cLinkPerson where a.ccuscode = '" + custcode + "'";
                DataTable dt = UFIDA.U8.DB.DbHelperSQL.QueryAsDT(sql, login.UFDataConnstringForNet);
                if (dt != null && dt.Rows.Count > 0)
                {
                    data.addresslist = new List<Address>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        Address add = new Address();
                        add.cAddCode = dr["cAddCode"].ObjToString();
                        add.cDeliverAdd = dr["cDeliverAdd"].ObjToString();
                        add.cLinkPerson = dr["cContactName"].ObjToString();
                        add.cMobilePhone = dr["cMobilePhone"].ObjToString();
                        data.addresslist.Add(add);
                    }
                }
                #endregion

                custdatas.Add(data);
            }
            else
            {
                custdatas.Add(new Customer { CustomerCode = custcode });
            }
            ApiRequest req = new ApiRequest();
            req.data = custdatas;//.ToJson();
            req.orgcode = login.get_cAcc_Id();
            req.primarykey = custcode;
            req.operation = operation;
            DebugWriteLog.WriteLine("客户档案", "GetCustJs", req.ToJson());
            return req.ToJson();
        }

        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs(login, domhead, 2);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                //var rr = PostHttpHelper.GetHttp(url, "", "application/json; charset=utf-8", 1000);
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }

        public bool Update_After_sh(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs_sh(login, domhead, 2);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                //var rr = PostHttpHelper.GetHttp(url, "", "application/json; charset=utf-8", 1000);
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }
        public bool Update_After_plm(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            Dictionary<string, string> js;
            try
            {
                js = GetCustJsPlm(login, domhead, 0);
                //不是qz直接返回true
                if (js == null)
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServerDic(url, js, "application/x-www-form-urlencoded");
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误"  + ex.Message;
                DebugWriteLog.WriteLine("InventoryPlugin", "异常", ex );
            }
            return bresult;
        }

        private Dictionary<string, string> GetCustJsPlm(clsLogin loginObj, MSXML2.IXMLDOMDocument2 domhead, int operation)
        {
            try
            {
                var datatable = Common.GetPlmUrl(constr, loginObj.get_cAcc_Id()).Tables[0];
                var datarow = datatable.Rows[0];
                url = datarow[1].ObjToString() + "IF_04?";

                string ccuscode = domhead.selectSingleNode("//ccuscode") == null ? "" : domhead.selectSingleNode("//ccuscode").nodeTypedValue.ObjToStringNull();//客户编码
                string ccusname = domhead.selectSingleNode("//ccusname") == null ? "" : domhead.selectSingleNode("//ccusname").nodeTypedValue.ObjToStringNull();//客户全称 
                string ccusabbname = domhead.selectSingleNode("//ccusabbname") == null ? "" : domhead.selectSingleNode("//ccusabbname").nodeTypedValue.ObjToStringNull();//客户简称
                string customerkcode = domhead.selectSingleNode("//customerkcode ") == null ? "" : domhead.selectSingleNode("//customerkcode ").nodeTypedValue.ObjToStringNull();//客户等级
                string ccusdefine1 = domhead.selectSingleNode("//ccusdefine1") == null ? "" : domhead.selectSingleNode("//ccusdefine1").nodeTypedValue.ObjToStringNull();//临时编码
                
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("fth4khbm", ccuscode);
                dic.Add("fth4khmc", ccusname);
                dic.Add("fth4khjc", ccusabbname);
                dic.Add("fth4khdj", customerkcode);
                dic.Add("itemid", ccusdefine1);               
                dic.Add("orgcode", loginObj.get_cAcc_Id());


                DebugWriteLog.WriteLine("InventoryPlugin", "GetCustJsPlm抛出参数", "ccuscode = " + ccuscode + "ccusname = " + ccusname + " customerkcode = " + customerkcode + " ccusdefine1 = " + ccusdefine1);
                return dic;
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("InventoryPlugin", "异常", e);
                throw e;
            }
        }


        public bool Insert_After_sh(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs_sh(login, domhead, 0);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }
        public bool Insert_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs(login, domhead, 0);
                //不是qz直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }
        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

            //从上下文获取U8Login对象
            U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
            if (login != null)
                constr = login.UFDataConnstringForNet;
            String js = "";
            try
            {
                js = GetCustJs(login, domhead, 1);
                //不是qz直接返回true
                //if (js == "Nopermission")
                //{
                //    return true;
                //}
                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                bresult = false;
                errMsg = "接口错误" + url + js + ex.Message;
            }
            return bresult;
        }
    }
}
